package com.tencreat.service.mall.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencreat.common.core.domain.model.LoginUser;
import com.tencreat.common.core.domain.model.ReqIdParam;
import com.tencreat.common.core.domain.model.ReqIdsParam;
import com.tencreat.common.utils.StringUtils;
import com.tencreat.domain.account.MallUser;
import com.tencreat.domain.mall.MallCoupon;
import com.tencreat.domain.mall.MallCouponUser;
import com.tencreat.domain.mall.MallGoods;
import com.tencreat.domain.mall.MallZone;
import com.tencreat.domain.mall.vo.ResOrderMallGoodsVO;
import com.tencreat.mapper.mall.MallCouponMapper;
import com.tencreat.service.account.IMallUserService;
import com.tencreat.service.mall.IMallCouponService;
import com.tencreat.service.mall.IMallCouponUserService;
import com.tencreat.service.mall.IMallGoodsService;
import com.tencreat.service.mall.IMallZoneService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 优惠券信息及规则Service业务层处理
 *
 * @author tencreat
 * @date 2021-08-13
 */

@Service
@RequiredArgsConstructor
public class MallCouponServiceImpl extends ServiceImpl<MallCouponMapper, MallCoupon> implements IMallCouponService {

    private final IMallCouponUserService couponUserService;
    private final IMallUserService mallUserService;
    //private final IMallZoneService zoneService; 专区
    private final IMallGoodsService mallGoodsService;

    /**
     * 查询优惠券信息及规则
     *
     * @param id 优惠券信息及规则ID
     * @return 优惠券信息及规则
     */
    @Override
    public MallCoupon selectMallCouponById(ReqIdParam id) {
        MallCoupon mallCoupon = baseMapper.selectById(id.getId());
        if (mallCoupon != null) {
            // 判断领取对象 指定用户
            if (mallCoupon.getType() == 3 && StringUtils.isNotEmpty(mallCoupon.getUuidList())) {
                List<Long> array = JSON.parseArray(mallCoupon.getUuidList(), Long.class);
                List<MallUser> users = mallUserService.lambdaQuery().in(MallUser::getUuid, array).list();
                mallCoupon.setUsers(users);
            }
            // 判断使用对象 专区
/*            if (mallCoupon.getGoodsType() == 1 && StringUtils.isNotEmpty(mallCoupon.getGoodsValue())) {
//                List<Long> array = JSON.parseArray(mallCoupon.getGoodsValue(), Long.class);
                String[] array = mallCoupon.getGoodsValue().split(",");
                List<MallZone> zones = zoneService.lambdaQuery().in(MallZone::getId, array).list();
                mallCoupon.setZones(zones);
            }*/
            // 判断使用对象 指定商品
            if (mallCoupon.getGoodsType() == 2 && StringUtils.isNotEmpty(mallCoupon.getGoodsValue())) {
                String[] array = mallCoupon.getGoodsValue().split(",");
                List<MallGoods> goods = mallGoodsService.lambdaQuery().in(MallGoods::getId, array).list();
                mallCoupon.setGoods(goods);
            }
            // 判断使用对象 商品
            if (mallCoupon.getGoodsType() == 0) {
                List<MallGoods> goods = mallGoodsService.lambdaQuery().list();
                mallCoupon.setGoods(goods);
            }
        }

        return mallCoupon;
    }

    /**
     * 查询优惠券信息及规则列表
     *
     * @param mallCoupon 优惠券信息及规则
     * @return 优惠券信息及规则
     */
    @Override
    public List<MallCoupon> selectMallCouponList(MallCoupon mallCoupon) {
        return baseMapper.selectList(Wrappers.query(mallCoupon));
    }

    /**
     * 新增优惠券信息及规则
     *
     * @param mallCoupon 优惠券信息及规则
     * @return 结果
     */
    @Override
    public int insertMallCoupon(MallCoupon mallCoupon, LoginUser user) {
        mallCoupon.setCreateTime(LocalDateTime.now());
        mallCoupon.setSurplus(mallCoupon.getTotal());
        if (mallCoupon.getUuids() != null && mallCoupon.getUuids().size() > 0) {
            String uuids = JSON.toJSONString(mallCoupon.getUuids());
            mallCoupon.setUuidList(uuids);
        }
        int insert = baseMapper.insert(mallCoupon);
        if (insert < 1) {
            return insert;
        }
        if (mallCoupon.getUuids() != null && mallCoupon.getUuids().size() > 0) {
            MallCouponUser mallCouponUser = new MallCouponUser();
            List<MallCouponUser> mallCouponUsers = new ArrayList<>();
            for (Long uuid:mallCoupon.getUuids()) {
                mallCouponUser = new MallCouponUser();
                mallCouponUser.setCouponId(mallCoupon.getId());
                mallCouponUser.setUuid(uuid);
                mallCouponUser.setStatus(0);
                mallCouponUser.setStartTime(mallCoupon.getStartTime());
                mallCouponUser.setEndTime(mallCoupon.getEndTime());
                mallCouponUser.setCreateTime(LocalDateTime.now());
                mallCouponUsers.add(mallCouponUser);
            }
//            couponUserService.grantCoupon(mallCoupon);
            couponUserService.saveBatch(mallCouponUsers);
        }
        return insert;
    }

    /**
     * 修改优惠券信息及规则
     *
     * @param mallCoupon 优惠券信息及规则
     * @return 结果
     */
    @Override
    public int updateMallCoupon(MallCoupon mallCoupon) {
        mallCoupon.setUpdateTime(LocalDateTime.now());
        return baseMapper.updateById(mallCoupon);
    }

    /**
     * 批量删除优惠券信息及规则
     *
     * @param ids 需要删除的优惠券信息及规则ID
     * @return 结果
     */
    @Override
    public int deleteMallCouponByIds(ReqIdsParam ids) {
        return baseMapper.deleteBatchIds(ids.getId());
    }


    @Override
    public List<MallCouponUser> couponUserList(List<ResOrderMallGoodsVO> goods, Long uuid) {
        List<MallCouponUser> list = couponUserService.lambdaQuery()
                .eq(MallCouponUser::getUuid, uuid)
                .gt(MallCouponUser::getStartTime, LocalDateTime.now())
                .le(MallCouponUser::getEndTime, LocalDateTime.now()).list();

        BigDecimal pricePay = BigDecimal.ZERO;

        List<MallGoods> mallGoods = mallGoodsService.lambdaQuery()
                .in(MallGoods::getId, goods.stream().mapToLong(ResOrderMallGoodsVO::getGoodsId)).list();

        List<Long> categoryList = mallGoods.stream().mapToLong(MallGoods::getCategoryId).boxed()
                .collect(Collectors.toList());
        List<Long> mallGoodList = mallGoods.stream().mapToLong(MallGoods::getId).boxed().collect(Collectors.toList());

        return list.stream().filter(i -> {
            MallCoupon byId = getById(i.getCouponId());
            if (byId.getStatus() == 0) {
                if (byId.getGoodsType() == 0) {
                    // 如果优惠券最低使用金额 <= 订单金额
                    return byId.getMin().compareTo(pricePay) < 1;
                } else if (byId.getGoodsType() == 1) {
                    List<Long> canUseCategoryList = JSONArray.parseArray(byId.getGoodsValue(), Long.class);
                    return canUseCategoryList.containsAll(categoryList);
                    /*
                     * categoryList. if()
                     */
                } else if (byId.getGoodsType() == 2) {
                    List<Long> canUseGoodList = JSONArray.parseArray(byId.getGoodsValue(), Long.class);
                    return canUseGoodList.containsAll(mallGoodList);
                }
            }
            return false;
        }).collect(Collectors.toList());

    }
}
